package com.iqilu.ksd.activity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ecloud.pulltozoomview.PullToZoomScrollViewEx;
import com.facebook.drawee.view.SimpleDraweeView;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.AuthActivity;
import com.iqilu.ksd.activity.BaseActivity;
import com.iqilu.ksd.activity.LoginActivity;
import com.iqilu.ksd.activity.MyPaikeActivity;
import com.iqilu.ksd.activity.MyFavoriteActivity;
import com.iqilu.ksd.activity.MyLiveActivity;
import com.iqilu.ksd.activity.MyMessageActivity;
import com.iqilu.ksd.activity.ScanActivity;
import com.iqilu.ksd.activity.SettingActivity;
import com.iqilu.ksd.activity.UserActivity;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.constant.UserRole;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.event.UnreadMsgEvent;
import com.iqilu.ksd.utils.SPUtils;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.Random;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/10/11.
 */

public class MyActivity extends BaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks {

    private UserBean user;
    private SimpleDraweeView imgAvatar;
    private ImageView btSetting;
    private ImageView btBack;
    private TextView tvName;
    private TextView tvAuth;
    private ImageView imgAuth;
    private ImageView imgMessage;
    private RelativeLayout layoutAuth;
    private RelativeLayout layoutLive;
    private RelativeLayout layoutClue;
    private RelativeLayout layoutSubs;
    private RelativeLayout layoutFav;
    private RelativeLayout layoutMessage;
    private RelativeLayout layoutScan;
    private PullToZoomScrollViewEx layZoom;

    private static final int PER_CAMERA_STORAGE = 101;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        setMessage();
        setUserInfo();
    }

    private void initView() {
        layZoom = getView(R.id.lay_zoom);
        user = ((MyApplication) getApplicationContext()).getUser();
        layZoom = getView(R.id.lay_zoom);
        View headView = LayoutInflater.from(this).inflate(R.layout.activity_my_head, null, false);
        View zoomView = LayoutInflater.from(this).inflate(R.layout.activity_my_zoom, null, false);
        View contentView = LayoutInflater.from(this).inflate(R.layout.activity_my_content, null, false);
        layZoom.setHeaderView(headView);
        layZoom.setZoomView(zoomView);
        layZoom.setScrollContentView(contentView);

        imgAvatar = (SimpleDraweeView) layZoom.getPullRootView().findViewById(R.id.img_avatar);
        btSetting = (ImageView) layZoom.getPullRootView().findViewById(R.id.bt_setting);
        btBack = (ImageView) layZoom.getPullRootView().findViewById(R.id.bt_back);
        tvName = (TextView) layZoom.getPullRootView().findViewById(R.id.txt_name);
        tvAuth = (TextView) layZoom.getPullRootView().findViewById(R.id.txt_auth);
        imgAuth = (ImageView) layZoom.getPullRootView().findViewById(R.id.img_auth);
        imgMessage = (ImageView) layZoom.getPullRootView().findViewById(R.id.img_message);
        layoutAuth = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_auth);
        layoutLive = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_live);
        layoutClue = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_clue);
        layoutSubs = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_subs);
        layoutFav = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_fav);
        layoutMessage = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_message);
        layoutScan = (RelativeLayout) layZoom.getPullRootView().findViewById(R.id.layout_scan);
        imgAvatar.setOnClickListener(this);
        btSetting.setOnClickListener(this);
        btBack.setOnClickListener(this);
        layoutLive.setOnClickListener(this);
        layoutClue.setOnClickListener(this);
        layoutSubs.setOnClickListener(this);
        layoutFav.setOnClickListener(this);
        layoutMessage.setOnClickListener(this);
        layoutAuth.setOnClickListener(this);
        layoutScan.setOnClickListener(this);
    }

    private void setMessage() {
        int count = SPUtils.getPref(this, UserInfo.MSGCOUNT, 0);
        if (count > 0) {
            imgMessage.setImageResource(R.drawable.ic_message_dot);
        } else {
            imgMessage.setImageResource(R.drawable.ic_message);
        }
    }

    private void setUserInfo() {
        setAvatar();
        int role = UserRole.NORMAL;
        if (user != null && user.getId() > 0) {
            tvName.setText("" + user.getNickname());
            role = user.getRole();
        } else {
            tvName.setText(getString(R.string.visitor));
        }
        setRole(role);
    }

    private void setAvatar() {
        if (user != null && !TextUtils.isEmpty(user.getAvatar())) {
            String path = user.getAvatar();
            int number = new Random().nextInt(100);
            if (path.contains("?")) {
                path = path + number;
            } else {
                path = path + "?time=" + number;
            }
            imgAvatar.setImageURI(Uri.parse(path));
        } else {
            imgAvatar.setImageURI(Uri.parse("res://" + getPackageName() + "/" + R.drawable.ic_avatar));
        }
    }

    private void setRole(int role) {
        switch (role) {
            case UserRole.AUTH:
                tvAuth.setText(getString(R.string.user_auth));
                imgAuth.setImageResource(R.drawable.bg_name_auth);
                break;
            case UserRole.REPORTER:
                tvAuth.setText(getString(R.string.user_auth));
                imgAuth.setImageResource(R.drawable.bg_name_vip);
                break;
            default:
                tvAuth.setText(getString(R.string.user_normal));
                imgAuth.setImageResource(R.drawable.bg_name_not_auth);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.img_avatar:
                if (user != null && user.getId() > 0) {
                    intent = new Intent(this, UserActivity.class);
                } else {
                    intent = new Intent(this, LoginActivity.class);
                }
                break;
            case R.id.bt_setting:
                intent = new Intent(this, SettingActivity.class);
                break;
            case R.id.bt_back:
                finish();
                break;
            case R.id.layout_live:
                if (user == null || user.getId() == 0) {
                    intent = new Intent(this, LoginActivity.class);
                } else {
                    intent = new Intent(this, MyLiveActivity.class);
                }
                break;
            case R.id.layout_clue:
                if (user == null || user.getId() == 0) {
                    intent = new Intent(this, LoginActivity.class);
                } else {
                    intent = new Intent(this, MyPaikeActivity.class);
                }
                break;
            case R.id.layout_subs:
                if (user == null || user.getId() == 0) {
                    intent = new Intent(this, LoginActivity.class);
                } else {
                    intent = new Intent(this, MySubsActivity.class);
                }
                break;
            case R.id.layout_fav:
                if (user == null || user.getId() == 0) {
                    intent = new Intent(this, LoginActivity.class);
                } else {
                    intent = new Intent(this, MyFavoriteActivity.class);
                }
                break;
            case R.id.layout_message:
                if (user == null || user.getId() == 0) {
                    intent = new Intent(this, LoginActivity.class);
                } else {
                    intent = new Intent(this, MyMessageActivity.class);
                }
                break;
            case R.id.layout_auth:
                if (user != null && user.getRole() == UserRole.NORMAL) {
                    intent = new Intent(this, AuthActivity.class);
                }
                break;
            case R.id.layout_scan:
                startScan();
                break;
            default:
                break;
        }
        if (intent != null) {
            startActivity(intent);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessage(ChangeUserInfoEvent event) {
        user = ((MyApplication) getApplicationContext()).getUser();
        setUserInfo();

    }

    // 有未读消息
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessage(UnreadMsgEvent event) {
        if (event.getCount() > 0) {
            imgMessage.setImageResource(R.drawable.ic_message_dot);
        } else {
            imgMessage.setImageResource(R.drawable.ic_message);
        }
    }

    @AfterPermissionGranted(PER_CAMERA_STORAGE)
    private void startScan() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            startActivity(new Intent(this, ScanActivity.class));
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_camera_storage), PER_CAMERA_STORAGE, perms);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_camera))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}
